package com.pad.dpscn.daag.sdk.core.aspect;

import java.util.concurrent.ConcurrentLinkedQueue;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.pad.dpscn.daag.sdk.common.enums.ErrorCodeEnum;
import com.pad.dpscn.daag.sdk.common.exception.DaagException;
import com.pad.dpscn.daag.sdk.common.message.MqMessage;
import com.pad.dpscn.daag.sdk.core.async.AsyncQueryDbAndSendMsgService;
import com.pad.dpscn.daag.sdk.core.interceptor.MybatisMapperInterceptor;
/**
 * 
 * com.pad.dpscn.daag.sdk.core.aspect  
 *  
 * <p>  
 * Description: 声明这是一个面向切面编程（AOP）的切面类  
 * </p>  
 *  
 * @author yangdezhao
 * @since 2024年3月11日  
 * @version 1.0
 */
@Aspect
@Component
public class DataCaptureAspect {

	private static final Log log = LogFactory.getLog(DataCaptureAspect.class);

	@Autowired
	private AsyncQueryDbAndSendMsgService asyncQueryDbAndSendMsgService;

	@Autowired
	private MybatisMapperInterceptor mybatisMapperInterceptor;

	@Pointcut("@within(com.pad.dpscn.daag.sdk.core.annotation.DataSendPosition)")
	public void dataSendPositionPointCut() {
		// 这里不执行任何操作，只是定义切入点
	}

	// 环绕注入
	@Around("dataSendPositionPointCut()")
	public Object around(ProceedingJoinPoint point) throws Throwable {
		try {
			log.info("Matched method: {} " + point.getSignature().getName() + " in class: {} "
					+ point.getTarget().getClass().getName());
			return point.proceed();
		} catch (Throwable e) {
			log.error("point.proceed()", e);
			mybatisMapperInterceptor.getDataQueue().clear();
		}
		return point;

	}

	@AfterReturning(returning = "ret", pointcut = "dataSendPositionPointCut()")
	public void doAfterReturning(Object ret) {
		// 执行后置逻辑，无论目标方法是否抛出异常，这里的代码都会执行  
        // 调用异步查询数据库并发送消息的方法  
		asyncQueryDbAndSendMsg();
	}

	/**
	 * 私有方法，用于异步查询数据库并发送消息  
	 */
	private void asyncQueryDbAndSendMsg() {
		try {
			ConcurrentLinkedQueue<MqMessage> dataQueue = mybatisMapperInterceptor.getDataQueue();
			if (!dataQueue.isEmpty()) {
				asyncQueryDbAndSendMsgService.asyncQueryDbAndSendMsg(dataQueue);
			}
		} catch (Exception e) {
			log.error("异步数据提交失败", e);
			throw new DaagException(ErrorCodeEnum.ASYNC_QUERY_DB_AND_SEND_MSG_ERROR);
		}
	}
}
